package com.lyn.usbfile;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import me.jahnen.libaums.core.UsbMassStorageDevice;
import me.jahnen.libaums.core.fs.FileSystem;
import me.jahnen.libaums.core.fs.UsbFile;
import me.jahnen.libaums.core.partition.Partition;

public class UsbFileManager implements USBBroadCastReceiver.UsbListener {

    private final static String TAG="UsbFileManager";
    private final static Object mLock = new Object();
    @SuppressLint("StaticFieldLeak")
    private static UsbFileManager mInstance;
    private final Context context;
    private USBBroadCastReceiver.UsbListener usbListener;

    public static UsbFileManager getInstance(Context context) {
        synchronized (mLock) {
            if (mInstance == null) {
                mInstance = new UsbFileManager(context);
            }
            return mInstance;
        }
    }

    public UsbFileManager(Context context) {
        this.context = context;
        registerReceiver(this);
    }

    public void setUsbListener(USBBroadCastReceiver.UsbListener usbListener) {
        this.usbListener = usbListener;
    }

    private void registerReceiver(USBBroadCastReceiver.UsbListener usbListener) {
        USBBroadCastReceiver usbBroadCastReceiver = new USBBroadCastReceiver();
        usbBroadCastReceiver.setUsbListener(usbListener);
        //监听otg插入 拔出
        IntentFilter usbDeviceStateFilter = new IntentFilter();
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        context.registerReceiver(usbBroadCastReceiver, usbDeviceStateFilter);
        //注册监听自定义广播
        IntentFilter filter = new IntentFilter(USBBroadCastReceiver.ACTION_USB_PERMISSION);
        context.registerReceiver(usbBroadCastReceiver, filter);
    }

    @Override
    public void insertUsb(UsbDevice usbDevice) {
        if (this.usbListener!=null){
            this.usbListener.insertUsb(usbDevice);
        }
    }

    @Override
    public void removeUsb(UsbDevice usbDevice) {
        if (this.usbListener!=null){
            this.usbListener.removeUsb(usbDevice);
        }
    }

    @Override
    public void getReadUsbPermission(UsbDevice usbDevice) {
        if (this.usbListener!=null){
            this.usbListener.getReadUsbPermission(usbDevice);
        }
    }

    @Override
    public void failedReadUsb(UsbDevice usbDevice) {
        if (this.usbListener!=null){
            this.usbListener.failedReadUsb(usbDevice);
        }
    }

    public List<UsbMassStorageDevice> getUsbMassStorageDevices() {
        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        //获取存储设备
        UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(context);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(USBBroadCastReceiver.ACTION_USB_PERMISSION), 0);
        //可能有几个 一般只有一个 因为大部分手机只有1个otg插口
        for (UsbMassStorageDevice device : storageDevices) {
            //有就直接读取设备是否有权限
            if (!usbManager.hasPermission(device.getUsbDevice())) {
                //没有权限请求权限
                usbManager.requestPermission(device.getUsbDevice(), pendingIntent);
            }
        }
        return Arrays.asList(storageDevices);
    }

    /**
     * 获取device 根目录文件
     *
     * @param usbMassStorageDevice USB 存储设备
     * @return 设备根目录下文件列表
     */
    public UsbFile getRootUsbFile(UsbMassStorageDevice usbMassStorageDevice) {
        try {
            usbMassStorageDevice.init();
            Partition partition = usbMassStorageDevice.getPartitions().get(0);
            FileSystem currentFs = partition.getFileSystem();
            return currentFs.getRootDirectory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取文件夹文件列表
     * @param usbFile
     * @return
     */
    public ArrayList<UsbFile> readUsbDirectory(UsbFile usbFile){
        ArrayList<UsbFile> usbFileArrayList=new ArrayList<>();
        UsbFile[] usbFiles = new UsbFile[0];
        try {
            usbFiles = usbFile.listFiles();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (UsbFile file:usbFiles){
            if (file.isDirectory()){
                usbFileArrayList.add(file);
            }
        }
        for (UsbFile file:usbFiles){
            if (!file.isDirectory()){
                usbFileArrayList.add(file);
            }
        }
        return usbFileArrayList;
    }


}
